package cn.ad.param;

import cn.ad.common.DataUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AccountTransferQuery extends AbstractPagingSortParam{
	/**
	 * 开始日期
	 */
	@NotNull
	@NotEmpty
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date startDate;
	/**
	 * 结束日期
	 */
	@NotNull
	@NotEmpty
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date endDate;

	public Date getStartDate() {
		return startDate == null ?  getDateBefore(new Date(),7): startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {

		return endDate == null ? new Date() : endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	/**
	 * 默认按创建排序
	 */
	@Override
	@NotNull
	@NotEmpty
	public String getSortby() {
		return DataUtils.isNull(super.getSortby()) ? "create_time" : super.getSortby();
	}

	/**
	 * 默认按降序排序
	 */
	@Override
	@NotNull
	@NotEmpty
	public ORDER getOrder() {
		return super.getOrder() == null ? ORDER.desc : super.getOrder();
	}

	public Map<String,Object> getSearchMap() throws ParseException {
		Map<String,Object> map = new HashMap<String,Object>();
		if(DataUtils.compareDate(startDate,endDate)) {
			map.put("startDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd").format(this.getStartDate())+" 00:00:00"));
		}else {
			map.put("startDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd").format(this.getStartDate())+" 23:59:59"));
		}
		map.put("endDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd").format(this.getEndDate())+" 23:59:59"));
		map.put("sortby", this.getSortby());
		map.put("order", this.getOrder());
		return map;
	}

	public static Date getDateBefore(Date d, int day) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		return now.getTime();
	}

}
